package com.java2401.yangnan.handler;

import com.java2401.yangnan.pojo.UserLogin;
import com.java2401.yangnan.service.UserLoginService;
import com.java2401.yangnan.util.CommonResult;
import com.java2401.yangnan.util.MD5Util;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

@RequestMapping("system")
@Controller
public class UserLoginHandler {
    @Resource
    UserLoginService userLoginService;
    @RequestMapping("/login")
    @ResponseBody
    public CommonResult<UserLogin> login(
            @RequestParam("username") String username,
            @RequestParam("password") String password,
            HttpServletRequest request
            ){
        UserLogin s = userLoginService.login(username, password);
        System.out.println("-----" + s);
        request.getSession().setAttribute("username", s.getUsername());
        if(s != null){
            // 登录成功，返回成功信息和用户信息
            return CommonResult.success(s);
        }else {
            // 登录失败，返回错误信息
            return CommonResult.failed("用户名或密码错误");
        }
    }

    @RequestMapping("/register")
    @ResponseBody
    public Integer register(@RequestBody UserLogin userLogin){
        UserLogin select = userLoginService.select(userLogin.getUsername());
        if(select == null){
            Integer register = userLoginService.register(userLogin.getUsername(), MD5Util.encode(userLogin.getPassword()));
            return register;
        }else {
            return  -1;
        }
    }

    @RequestMapping("/yanzheng")
    @ResponseBody
    public CommonResult<String> yanzheng(
            HttpServletRequest request
    ){
        Object username = request.getSession().getAttribute("username");
        System.out.println("--------------------------username" + username);
        if(username != null){
            // 登录成功，返回成功信息和用户信息

            return CommonResult.success("用户已登录");
        }else {
            // 登录失败，返回错误信息
            return CommonResult.failed("用户未登录");
        }
    }

    @RequestMapping("/exit")
    @ResponseBody
    public void exit(
            HttpServletRequest request
    ){
        request.getSession().setAttribute("username", null);
    }
}
